﻿using SqlSugar;
using Zhp.Entity.Sys;
using Zhp.SqlSugar.Trigger;
using Zhp.SqlSugar.Trigger.Core;

namespace Zhp.Trigger.Service
{
    [Trigger(nameof(SysMenu))]
    public sealed class SysMenuTrigger : BaseTriggerService<SysMenu, long>
    {
        public override async Task InsertedAsync(ISqlSugarClient context, SysMenu entity)
        {
            await SetMenuPathLevel(context, entity);
            await context.Insertable(entity).ExecuteCommandAsync();
        }

        public override async Task UpdatedAsync(ISqlSugarClient context, SysMenu entity)
        {
            await SetMenuPathLevel(context, entity);
            await context.Updateable(entity).ExecuteCommandAsync();
        }

        /// <summary>
        /// 更新路径和层级
        /// </summary>
        /// <param name="entity"></param>
        private async Task SetMenuPathLevel(ISqlSugarClient context, SysMenu entity)
        {
            var pIds = new List<long>();
            if (entity.ParentId.HasValue)
            {
                var parentList = await context.Queryable<SysMenu>().ToParentListAsync(x => x.ParentId, entity.Id);
                pIds = parentList.OrderBy(x => x.Level).Select(x => x.Id).ToList();
            }
            entity.Path = string.Join(";", pIds);
            entity.Level = pIds.Count + 1;
        }
    }
}
